package com.conversationboard.view;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.conversationboard.formatter.Formatter;
import com.conversationboard.logger.LogMessageType;
import com.conversationboard.model.LogMessage;

public class LogDisplay {

	private static Pattern pattern = Pattern.compile("(com\\.conversationboard.*)", (Pattern.CASE_INSENSITIVE));


	private static String processErrorMessage(String message) {

		Matcher matcher = pattern.matcher(message);
		String replaced = matcher.replaceAll("<span class=\"red\">$1</span>");

		return replaced;
	}


	public static String display(List<LogMessage> logMessages) {

		StringBuilder buffer = new StringBuilder();

		for (LogMessage logMessage : logMessages) {

			switch (logMessage.getType()) {

				case USER:
					buffer.append("<div class='userlog'><strong>USER: </strong>");
					break;

				case SERVER:
					buffer.append("<div class='serverlog'><strong>SERVER: </strong>");
					break;

				case SYSTEM:
					buffer.append("<div class='systemlog'><strong>SYSTEM: </strong>");
					break;

				case DEBUG:
					buffer.append("<div class='debuglog'><strong>DEBUG: </strong>");
					break;
			}

			buffer.append("<strong>");
			buffer.append(logMessage.getTimestamp());

			if (!logMessage.getLoginId().equalsIgnoreCase("Anonymous")) {
				buffer.append(": " + logMessage.getLoginId());
			}
			buffer.append("<br />");

			buffer.append("</strong>");

			/* Only format as HTML if it's a user message or it contains the text exception */

			if ((logMessage.getType() == LogMessageType.USER) || (logMessage.getMessage().contains("xception"))) {
				buffer.append("<span class='logmessage'>" + Formatter.escapeHtml(logMessage.getMessage()) + "</span>");
			} else {
				buffer.append("<span class='logmessage'>" + logMessage.getMessage() + "</span>");
			}

			buffer.append("</div>");
		}

		String message = buffer.toString();
		message = LogDisplay.processErrorMessage(message);

		return message;

	}
}
